<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>计算两个日期之间的天数等</title>
  </head>
  <script>
    // 计算两个日期的天数
    function daysBetween(date1, date2) {
      date1 = new Date(date1);
      date2 = new Date(date2);
      const oneDay = 24 * 60 * 60 * 1000;
      const firstTime = date1.getTime();
      const seconedTime = date2.getTime();
      return Math.round((seconedTime - firstTime) / oneDay + 1);
    }
    const days = daysBetween("2024-6-1", "2024-6-5");

    function numberToChinese(num) {
      const digitMap = [
        "零",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九",
      ];
      const unitMap = ["", "十", "百", "千", "万", "亿"];

      let chinese = "";
      let unitIndex = 0;

      if (num === 0) {
        return digitMap[0];
      }

      while (num > 0) {
        const digit = num % 10;
        if (digit !== 0 || chinese.length === 0 || chinese[0] !== digitMap[0]) {
          chinese = digitMap[digit] + unitMap[unitIndex] + chinese;
        }
        num = Math.floor(num / 10);
        unitIndex++;
      }

      return chinese;
    }
    const daychinese = numberToChinese(3);
    console.log(days, daychinese);

    // 计算两个日期中间的小时
    function hoursBetweenDates(date1, date2) {
      const oneDay = 24; // 每天小时数
      const oneHour = 60 * 60 * 1000; // 每小时毫秒数

      // 将日期转换为时间戳
      const timestamp1 = date1.getTime();
      const timestamp2 = date2.getTime();

      // 计算两个时间戳之间的差值
      const difference = Math.abs(timestamp1 - timestamp2);

      // 将差值转换为小时
      const hours = difference / oneHour;
      //可以直接return hours
      return Math.floor(hours);
    }

    // 示例使用
    const date1 = new Date("2023-04-01T12:00:00");
    const date2 = new Date("2023-04-02T15:30:00");

    const hoursBetween = hoursBetweenDates(date1, date2);
    console.log(hoursBetween); // 输出: 6.5 小时
  </script>
  <body></body>
</html>
